<?php
namespace app\admin\model;

class Statistic extends Base{

    protected $name = 'statistic';
    const SZ = 'https://www.szse.cn/api/report/index/overview/onepersistenthour/szse';
    const SH = 'http://www.sse.com.cn';

    public function initialize(){

    	$this->statisticDb = db('statistic');
    }

    public function delStockShareholder($id=0){
        $this->where(['id'=>$id])->delete();
    }

    public function statisticList(){

    	return $this->statisticDb->order('year DESC')->select();
    }

    public function statisticDetail($where=[]){

    	return $this->where($where)->find();
    }

    public function updateSecurityData($arrData=[]){

		$arr = [];
		if($arrData['platform_type']=='sh'){

			$sh = '';
			$sh = $this->getUrl(self::SH, 0);
			preg_match("/home_sjtj.mkt_value = '(.*)'/", $sh, $val);
			$arr['year']= date('Y', time());
			$arr['val'] = trim($val[1]);
			$this->where(['sta_id'=>$arrData['sta_id']])->update($arr);

		}else if($arrData['platform_type']=='sz'){
			
			$sz = '';
			$sz = $this->getUrl(self::SZ, 0);
			$sz = json_decode($sz, true);
			$arr['year'] = date('Y', strtotime($sz['result']['basicmap']['time']));
			$arr['val'] = $sz['result']['basicmap']['main'][2]['value'];
			$this->where(['sta_id'=>$arrData['sta_id']])->update($arr);
		}else if($arrData['platform_type']=='GDP'){
			
			die("GDP");
		}
    }

    public function saveGdp($id=null, $arr=[]){

    	if($id==null){ 

    		$this->insert($arr);
    	}else{

    		$this->where(['sta_id'=>$id])->update($arr);
    	}
    }

    //sum
    public function sumCLl(){

        $reVal = [];
        $reVal['sh']= $this->where(['platform_type'=>'sh'])->field('platform_type, val')->find()->toArray()['val'];
        $reVal['sz']= $this->where(['platform_type'=>'sz'])->field('platform_type, val')->find()->toArray()['val'];
        $gdp = [];
        $gdp = $this->where(['platform_type'=>'gdp'])->field('platform_type, val')->select();
        $reVal['gdp']= 0; 
        foreach ($gdp AS $v) {
            
            $reVal['gdp'] += floatval($v['val']);
        }

        $reVal['sum'] = (floatval($reVal['sh'])+floatval($reVal['sz']))/floatval($reVal['gdp']);
        $reVal['sum'] = sprintf("%.2f", $reVal['sum']);
        return $reVal;
    }
}